// 1.进入页面首先要获取部门信息和职务信息，绑定执行的下拉框中
//2.获取用户输入信息
// 格式校验
// 发送给服务器对应的请求
let useraddMoudle=(function(){
    let $username=$('.username'),
    $spanusername=$('.spanusername'),
    $man=$('#man'),
    $woman=$('#woman'),
    $useremail=$('.useremail'),
    $spanuseremail=$('.spanuseremail'),
    $userphone=$('.userphone'),
    $spanuserphone=$('.spanuserphone'), 
    $userdepartment=$('.userdepartment'),
    $userjob=$('.userjob'),
    $userdesc=$('.userdesc'),
    $submit=$('.submit');

    let userId=null;
    //绑定部门和职务的信息
     async function bindDepartAndJob(){

        //首先看本地是否存在缓存信息，如果存在，在验证时效性，不存在或者过期了，我们重新
        // 发送请求，否则直接用本地的信息即可
        let departmentData=null,
            jobData=null;
            isStorage=false;
            let departmentAndjob=localStorage.getItem('departmentAndjob');
            if(departmentAndjob){
                departmentAndjob=JSON.parse(departmentAndjob);
                if(new Date().getTime()-departmentAndjob.time<86400000){
                    [departmentData,jobData]=departmentAndjob.data;
                    isStorage=true;
                }
            }

            // 处理使用非缓存的信息，重新请求
            if(!isStorage){
                let [departmentData,jobData]= await axios.all([
                    axios.get('/department/list'),
                    axios.get('/job/list')
                ])
                //获取信息后先把信息缓存到本地(时效性1天)
                localStorage.setItem('departmentAndjob',JSON.stringify({
                    time: new Date().getTime(),
                    data:[departmentData,jobData]
                }))  
            }
        
            if(departmentData.code==0){
            departmentData=departmentData.data;
            let str=``;
            departmentData.forEach(item => {
                str +=`<option value="${item.id}">${item.name}</option>`
            });
            $userdepartment.html(str);
        }
        if(jobData.code==0){
            jobData=jobData.data;
            let str=``;
            jobData.forEach(item => {
                str +=`<option value="${item.id}">${item.name}</option>`
            });
            $userjob.html(str);
        }
    }


    //表单校验
    function checkName(){
        let val=$username.val().trim();
        if(val.length==0){
            $spanusername.html('小主，当前是必填项');
            return false;
        }
        if(!/^[\u4e00-\u9fa5]{2,10}$/.test()){
            $spanusername.html('小主，请填写真实姓名');
            return false;
        }
        $spanusername.html('');
        return true;
    }
    
    function checkEmail(){
        let val=$useremail.val().trim();
        if(val.length==0){
            $spanuseremail.html('小主，当前是必填项');
            return false;
        }
        if(!/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test()){
            $spanuseremail.html('小主，请填写真实邮箱');
            return false;
        }
    }
    function checkPhone(){
        let val=$userphone.val().trim();
        if(val.length==0){
            $spanuserphone.html('小主，当前是必填项');
            return false;
        }
        if(!/^[1][3,4,5,7,8,9][0-9]{9}$/.test()){
            $spanuserphone.html('小主，请填写真实电话');
            return false;
        }
    }
     
    // 点击确认提交按钮
    async function submitHandle(){
        //重复表单校验
        if(!checkName()||!checkPhone ||!checkEmail){
            return;
        }

        //获取用户输入的信息
        let params={
            name:$username.val().trim(),
            sex:$man.prop('cheched') ? 0 : 1,
            email:$username.val().trim(),
            phone:$userphone.val().trim(),
            departmentId:$userdepartment.val(),
            jobId:$userjob.val(),
            desc:$userdesc.val().trim()
        }


        //向服务器发送请求（区分新增还是修改）
        if(userId){
            //xiugai
            params.userId=userId;
            let result= await axios.post('/user/update',params);
                if(result.code==0){
                    alert('小主，您很棒，已成功修改一条数据');
                    window.location.href="userlist.html";
                    return;
                }
                alert('小主，当前网络繁忙，稍后再试');
            return;


        }
        // /新增
        let result= await axios.post('/user/add',params);
        if(result.code==0){
            alert('小主，您很棒，已成功新增一条数据');
            window.location.href="userlist.html";
            return;
        }
        alert('小主，当前网络繁忙，稍后再试');
    }

    //从服务器获取用户的基本信息，绑定在对应的文本框中

    async function queryBaseInfo(){
        let result= await axios.get('/user/info',{
            params:{
                userId
            }
        });
        if(result.code==0){
            result=result.data;
            $username.val(result.name);
            result.sex==0?$man.prop('checked',true):$woman.prop('checked',true);
            $useremail.val(result.email);
            $userphone.val(result.phone);
            $userdepartment.val(result.departmentId);
            $userjob.val(result.jobId);
            $userdesc.val(result.desc);
            return;
        };
        alert('小主，当前要编辑的员工不存在，请查证！');
        userId=null;
    }
    return {
        init(){
        
            bindDepartAndJob();

            //获取到传递的员工id ,从而获取员工的基本信息
            let params=window.location.href.queryURLParams();
            if(params.hasOwnProperty('id')){
                userId=params.id;
            }
            //文本框失去焦点的时候做表单校验
            $username.blur(checkName);
            $useremail.blur(checkEmail);
            $userphone.blur(checkPhone);
            submitHandle();

        }
    }
})();
useraddMoudle.init();